// src/utils/request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const service = axios.create({
    baseURL: '/api', // 可根据环境变量配置
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('adminToken')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => response,
    error => {
        const msg = error.response?.data?.message || '请求出错'
        ElMessage.error(msg)

        if (error.response?.status === 401) {
            localStorage.removeItem('adminToken')
            router.push('/admin/login')
        }

        return Promise.reject(error)
    }
)

export default service
